package com.yeswater.rabbitmq_spingboot.controller;

import com.yeswater.rabbitmq_spingboot.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 发送延时消息
 * localhost:8080/ttl/sendMsg/111
 * Author : yeswater
 */

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMessageController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        log.info("当前时间: {},发送一条信息给两个TTL 队列 : {}", new Date(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为 10s 的队列: " + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为 20s 的队列: " + message);
    }

    @GetMapping("/sendTTLMsg/{message}/{ttl}")
    public void sendTTlMsg(@PathVariable String message,
                           @PathVariable String ttl) {
        log.info("当前时间: {},发送一条信息给队列C, TTL 为 : {} 毫秒,消息为 : {}", new Date(), ttl, message);
        rabbitTemplate.convertAndSend("X", "XC", "消息来自 sendTTlMsg 的队列: " + message, (msg) -> {
            msg.getMessageProperties().setExpiration(ttl);
            // msg.getMessageProperties().setDelay(Integer.parseInt(ttl));
            return msg;
        });
    }

    @GetMapping("/sendDelayedMsg/{message}/{delayTime}")
    public void sendDelayedMsg(@PathVariable String message,
                               @PathVariable Integer delayTime) {
        log.info("当前时间: {},发送一条信息给队列C, TTL 为 : {} 毫秒,消息为 : {}", new Date(), delayTime, message);
        rabbitTemplate.convertAndSend(
                DelayedQueueConfig.DELAYED_EXCHANGE_NAME,
                DelayedQueueConfig.DELAYED_ROUTING_KEY,
                "消息来自 sendTTlMsg 的队列: " + message, (msg) -> {
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });
    }

}
